Skip to content

feat(stack-encrypt)!: encrypt and decrypt one value known only at run time, and bound the typed decrypt to a scalar - #2011

Merged
coderdan merged 20 commits into
nextfrom
feat/dynamic-single-value
Nov 29, 2026
Merged

coderdan merged 20 commits into
nextfrom
feat/dynamic-single-value

Conversation

@coderdan

@coderdan coderdan commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The engine can now encrypt and decrypt one value whose type is known only at run time. A language SDK passes a frame, and gets back the same kind of Ciphertext that Rust's keyset.encrypt(value) makes. The typed keyset.decrypt::<T> now accepts only a target that one scalar can build. So keyset.decrypt::<Vec<String>> is a compile error, not a failure after the key request.

Closes #2009.

Changes

  1. Run-time API: stack_encrypt::dynamic::value.
    • encrypt(keyset, value: Frame<'_>, kind: Option<ValueKind>) returns the pending Ciphertext.
    • decrypt(cipher_ref, ciphertext, kind) returns the pending OwnedFrame.
    • Each has a _with_context form. There is no batch form, because the typed interface has none. A caller merges several pending results with Pending::all. The merged request makes one key request.
    • Encrypt refuses, before any key request: an array, an object, a passthrough, a null (plain or typed), and JavaScript's undefined. The new reason for each of them is not_a_scalar.
    • With a declared kind, a value converts by the exact rules of a record write.
    • Json on encrypt takes the document as a text or bytes leaf, checks it, and stores it as JsonPlaintext is stored.
    • Decrypt converts nothing. A value of another kind is OpenedType. That error names only the kind expected. Json returns the document's text.
    • It runs the typed call's own operation. There is no wrapper type, and no Scalar impl for a frame.
  2. A refusal has its own error, and the error names the kind of the value.
    • dynamic::Error::Value { reason, found } has the code stack_encrypt::dynamic_value.
    • found is the kind of the value to encrypt, as a dynamic::Found. The record errors of fix(stack-encrypt): say what a record found where it takes an object, and where #2005 name a kind in the same way. The kind is in Error::found(), in the payload field found, and in the message.
    • Example messages:
      • "the value to encrypt is an array, not a scalar"
      • "the value to encrypt is a string, and does not convert exactly to the declared kind"
    • The error never contains the value. A refused decrypt never names the kind of the decrypted value.
  3. A scalar bound on the typed decrypt, with no code for the user to write.
    • ScalarTarget marks a decrypt target that one scalar builds. It comes from the target's sink type: a new sink marker, TakesScalar, and one blanket impl.
    • #[derive(Decrypt)] struct Email(String); is a ScalarTarget with no other code. So are Option<T> and Protected<T> of one, and OwnedFrame.
    • Nobody can implement ScalarTarget by hand. A private supertrait rejects it.
    • A refused target gets an error in Stack Encrypt's terms: "Vec<String> cannot be decrypted from one Ciphertext". The notes list the conditions a target must meet, and describe DecryptFrom, keyset.decrypt_tree, and OpaqueBlob<T> for the other cases. The error names no vitaminc type.
    • These no longer compile as a Ciphertext's target:
      • a Vec other than Vec<u8>
      • a map
      • a derived struct with named fields
      • a newtype over any of them
  4. TypeScript addon. OneValue is deleted. seal calls value::encrypt for each value and merges the results with Pending::all. Behaviour and native.d.ts are unchanged.
  5. Conformance. A single-value-v1 profile with 71 cases and 7 batches, a contract document, and a Rust runner. Each refused case checks the code, the reason, and the found kind. The Go runner is recorded as pending (Go SDK: encrypt one value into one ciphertext, as Rust and TypeScript do #2010).
  6. Docs. Rustdoc with runnable examples, a section in docs/language-integration.md, an amendment to ADR-0012, and CHANGELOG entries for stack-encrypt (Added, Breaking) and vitaminc-aead. The prose follows the plain-language skill.

The run-time ciphertext cannot be compared with the typed one byte for byte

#2009 asked for the same bytes as keyset.encrypt. That is not possible: each sealed leaf has a fresh random nonce, so the same call twice gives different bytes. tests/single_value.rs compares everything that the nonce does not change, for each kind:

  • the ciphertext's prefix before the AEAD output: format version, keyset, data-key IV, and key tag;
  • the total length;
  • the leaf's plaintext, decrypted with the kept data key;
  • that each interface decrypts the other's ciphertext.

string and json have one stored form

A JSON document is stored as checked text. So a declared kind on decrypt cannot tell a string from a JSON document when the text is valid JSON. Text such as 42 decrypts as json, and ada does not. The docs say this, and tests pin both.

Verification

Run locally on Rust 1.94.1.

  • Root workspace:
    • fmt
    • clippy with -D warnings, for all features, and for stack-encrypt with no default features
    • cargo test -p stack-encrypt with all features. This run includes the compile tests and doctests.
    • cargo test -p stack-encrypt with no default features
  • vitaminc-aead: tests under six feature sets: none, jiff, rust_decimal, uuid, hlist, and all.
  • recipher-frame and vitaminc-aead-derive: tests.
  • Rustdoc: public and private items, with -D warnings.
  • Mutation testing (--in-diff, the whole PR): 35 mutants, 21 caught, 14 that do not compile, 0 missed.
  • Other workspaces that compile the engine:
    • recipher-js: fmt, clippy, tests, and the addon's value tests
    • EQL: eql-bindings and the encryption tests
    • both Go guests: fmt, clippy for every feature set and wasm32, and tests
  • Script tests: the conformance suite. Biome on the changed JSON.
  • Not run: mise run test:conformance, the Go tests, and the guest wasm builds. CI runs them.

Related

Review notes

Open questions:

  1. The names: ScalarTarget, TakesScalar, and the module dynamic::value, beside the crate-root value module of Date, Decimal, and the others.
  2. Option<T> stays a typed decrypt target, because it works today for a leaf that encrypt_tree(None::<i64>) stored. The encrypt side's Scalar excludes Option, so the two sides are not symmetric.
  3. A scalar of an unknown logical type still encrypts when no kind is declared. The leaf format stores such a type by its id on purpose. So an older build can store a value of a type that a newer build added. It is refused with any declared kind.
  4. TakesScalar is not re-exported from stack-encrypt. An author of a hand-written sink imports it from vitaminc-aead. A derived type needs nothing.
  5. Both this PR and fix(stack-encrypt): encrypt a derived newtype with keyset.encrypt #2014 re-record two compile-test snapshots: opaque_blob_requires_zeroize.stderr and owned_collection_elements.stderr. The second to merge re-records them.

A sealed leaf holds one scalar or one null. A caller that opens exactly
one leaf had only `Decrypt` to bound its target on, and `Decrypt` also
covers a sequence, a map and a derived struct. Such a target opened the
leaf and was refused afterwards, so a mistake a compiler could catch was
found only after the plaintext was decrypted.

`ScalarTarget` is the decrypt-side counterpart of `Scalar`. It is
implemented for every `FromScalar` type, for an `Option` or a
`Protected` of a `ScalarTarget`, and for `OwnedFrame`, which one leaf
always builds. A `Vec` of anything but bytes, a map and a derived struct
do not implement it.

The trait is open, as `Scalar` is. A newtype that derives `Decrypt` over
a scalar adds an empty impl, because the derive cannot know that its
inner type is a scalar target.

Nothing in this crate bounds on the trait, so no existing code changes.
…time

`keyset.encrypt` takes a type whose borrow is a `Scalar`, which is a
promise the compiler checks. A language SDK holds a value as a frame and
learns its kind only when the code runs, and a frame can hold a list or
a map, so it is not a `Scalar`. Each SDK worked around that in its own
way: TypeScript wrapped the frame in a type of its own and claimed
`Scalar` for it, and Go sealed every value as a record of one field. So
the languages did not write the same thing for one value.

`dynamic::value` is the engine's own answer. `encrypt` takes a borrowed
`Frame` and an optional declared `ValueKind`, and walks the value into
the operation `keyset.encrypt` runs. So the ciphertext has the same leaf
under the same key request and context, and each language reads what
another wrote. `decrypt` opens a ciphertext into an `OwnedFrame` and can
check the kind it opens as. Both have a form with a context and a form
for many values in one key request.

A ciphertext holds one scalar. `encrypt` refuses an array, an object, a
passthrough and a null before any key is requested, with a reason that
says which was found: `Reason::Array`, `Reason::Object` and
`Reason::Null` are new. A null is refused because the typed call has no
nullable form either.

A declared kind converts a number by the rules a record's typed field
uses. The `json` kind takes a document as JSON text and seals it as
`JsonPlaintext` is sealed. Decrypt converts nothing, as a record does
not, and its refusal names only the kind that was expected.

The functions take frames and kinds and return ciphertexts. They add no
type that wraps a frame or a value.

Two ciphertexts of one value never have the same bytes, because each
sealed leaf carries a random AES-GCM nonce. `tests/single_value.rs`
holds the two interfaces to every other part: the keyset, the data
key's IV and tag, the length, and the plaintext of the leaf. It seals
each kind through both, each over a fresh deterministic key source of
one seed. The helpers that open a leaf with a kept key move from
`tests/value_bytes.rs` to `tests/common/leaves.rs` for that.
`OpaqueDecode` was implemented for every `Decrypt` type that is
`Zeroize`. So `keyset.decrypt::<Vec<String>>(ciphertext)` compiled,
requested a key, decrypted, and only then failed with
`Error::OpenedType`. It could never succeed, because a `Ciphertext`
holds one scalar.

`OpaqueDecode` is now bounded on Vitamin C's `ScalarTarget`. A `Vec` of
anything but bytes, a map and a derived struct no longer compile as the
target of `keyset.decrypt`, `decrypt_with_context` or
`T::decrypt_from(ciphertext, ..)`. Every target that could succeed still
compiles: the scalars, `JsonPlaintext`, the date, timestamp, decimal
and UUID values, a `Protected` or an `Option` of one, and `OwnedFrame`.
`Option<T>` stays because it does succeed today: it reads a sealed null
as `None`. `OpaqueBlob<T>` keeps its own impl.

`ScalarTarget` is re-exported at the crate root beside `Decrypt`, so
that the bound can be named from this crate. A newtype that derives
`Decrypt` over a scalar adds the marker by hand.

BREAKING CHANGE: a target that needs a container no longer compiles as
the target of a single `Ciphertext`. Decrypt a tree of leaves with
`keyset.decrypt_tree`, and a column of ciphertexts with
`Vec::<T>::decrypt_from`. A newtype that derives `Decrypt` over a scalar
needs `impl ScalarTarget for T {}`.
The addon wrapped each frame in a type of its own, `OneValue`, and
implemented vitaminc's `Scalar` for it so that the engine's typed
encrypt would take it. That claim was the addon's to keep true, and
every other language SDK would have needed its own copy.

The engine now has a run-time single-value encrypt and decrypt. The
addon calls them and `OneValue` is gone, with the `zeroize` dependency
only it used.

Behaviour is unchanged. This build still encrypts a string only: the
addon checks that first, so a caller still gets
`recipher_js::not_a_string`, and it declares the kind `string` to the
engine, which checks again. The frames are dropped, and so wiped, as
soon as the engine has read them, before the key request is awaited.
Decrypt declares no kind, because the type of a `Ciphertext<T>` is known
to TypeScript alone.
One value encrypted into one ciphertext is the simplest thing an SDK
does, and no shared case said what it must write. `single-value-v1`
gives each runner a value, the kind declared for it and a context. It
covers every scalar kind, the exact conversions a declared kind makes,
JSON documents, batches, and the refusals of an array, an object, a
passthrough, a null, `undefined` and a value of another kind.

The expected file is written by the Rust runner. It freezes each
input's frame, the plaintext each leaf is sealed with, and a ciphertext
every runner must open. Ciphertext bytes are never compared whole,
because each sealed leaf has a random nonce. A runner compares the
parts the nonce does not change.

The Rust runner also holds the run-time interface to the typed one for
every case a Rust type spells. `test:conformance` runs it. The Go runner
comes with the Go SDK's single-value calls (#2010), and the README and
the coverage map record it as pending.

The corpus's shared input reader takes a `uuid` input for this profile.
…thor

The guide to building a language integration said a binding does three
things, all through a record's plan. A binding can now also encrypt one
value into one ciphertext, with no plan, and a new SDK should reach for
the engine's call and not write its own.

The guide gains a section on `dynamic::value`, and its checklist names
the single-value conformance profile. The crate docs point a binding
author at the module from the section on language integrations.
@changeset-bot

changeset-bot Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: dacd89c

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai

coderabbitai Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI; Enforced overrides: Organization
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5982a0cd-6a6d-4701-85ec-19da3aa3228c

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review

@coderdan coderdan left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review (/code-review medium) of d2ce814. Seven findings: one important and four nits inline, and two nits outside the diff, below.

packages/stack-encrypt/src/refusal.rs:153 (outside the diff, nit). A single-value refusal reads as a record error: "record source does not fit the plan: a null where one value must be". value::encrypt reuses Error::Source, whose text is fixed to records and plans. This is open question 4 in the description.

packages/stack-encrypt/docs/adr/0012-owned-record-declarations.md:177 (outside the diff, nit). The ADR still says a single Ciphertext's bound is Decrypt + Zeroize, so Vec<String> "compiles, and opening refuses it", and that a compile error would need a new trait in Vitamin C. This PR adds that trait and changes the bound.

I will reply on each thread with what I changed.

Comment thread packages/vitaminc-aead/src/typed.rs Resolved
@github-actions

github-actions Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Mutation testing (cargo-mutants, --in-diff, stack-auth, stack-encrypt, stack-encrypt-jsonpath, vitaminc-aead, recipher-frame, vitaminc-aead-derive)

caught missed unviable timeout
20 0 15 0

Every mutant in the changed lines was caught by a test.

The run-time single-value encrypt refused a null and sealed JavaScript's
`undefined` when no kind was declared. `undefined` is most often a
property name spelt wrong, so sealing one stores a mistake as a real
ciphertext, and no typed call can read it back. A record's typed field
already refuses it for that reason.

`dynamic::value::encrypt` now refuses `undefined` with
`Reason::Undefined`, with a declared kind and with none, before any key
is requested.

Two other values have no kind and reached the same arm:

- A scalar of a logical type this build does not know. It is still
  sealed as it arrived when no kind is declared. The leaf format carries
  such a type by its id so that a value of a newer type survives an
  older build, the leaf encoder writes it, and it opens again with no
  declared kind. A declared kind refuses it. Tests now pin both.
- A known logical type over a value it does not admit. No frame holds
  one: the frame writer refuses to write it and the frame reader refuses
  its bytes. A test pins that it cannot reach `encrypt`.

The conformance case `as-is-undefined` becomes the refused case
`undefined-no-kind`. On an update, the Rust runner now keeps the frozen
ciphertext of a case whose frame and leaf have not changed, and checks
it as any run does. So a regeneration changes only the cases that
changed, and a frozen ciphertext stays frozen.
The docs of the run-time decrypt said a value of another kind is
refused. But `json` is a declared kind, and not a stored one: a document
is stored as a text leaf that holds its JSON text, which is how a string
is stored. So a sealed document opens as `string`, and a sealed string
whose text is a JSON document opens as `json`. A kind check cannot tell
the two apart, and the docs now say so.

They also say what decrypt as `json` does: it checks that the text
parses, and returns the document as the engine writes it. That text can
differ from the text that was sealed as a string.

The conformance case `as-is-string` listed `json` among the kinds it is
refused as, which read as if every string were. That refusal moves to
its own case, `string-not-json-text`. Two new cases show a string whose
text is a document opening as `json`, and `json-given-string` shows a
document opening as `string`. A case can now list kinds it opens as,
with the value for each. Rust tests pin the same behaviour.
ADR-0012 said the target of a single `Ciphertext` is bounded on
`Decrypt + Zeroize`, that a `Vec<String>` target compiles and is refused
when it opens, and that a compile error would need a new trait in
Vitamin C. That trait now exists and the bound uses it, so the
paragraph described the code as it was.

The amendment records the new bound, `ScalarTarget + Zeroize`, and
keeps the original text beside it, as the other ADRs do.
The checklist for a new binding listed single values among the profiles
that Go's `*conformance_test.go` files run. Go has no single-value
runner yet, so a reader looking for one to follow would find none.

The checklist now names the Rust runner as the one to follow. The
script test that asserts the conformance task was titled "runs all
profiles in both languages" and included the single-value runner. It is
split: one test for the profiles that have both runners, and one for
the single-value profile, which also holds the README to recording the
Go runner as pending.
The addon sealed its values through the engine's batch form of the
run-time single-value encrypt. That form is being removed: the engine's
`Pending::all` already merges any pending calls into one key request, so
a batch form of each call adds nothing.

`seal` now calls `value::encrypt` for each frame and merges the calls
with `Pending::all`. It is still one key request, and the frames are
still dropped before it is awaited. `unseal` goes back to
`Vec::<OwnedFrame>::decrypt_from`, the engine's typed decrypt of a
column into frames: it checks no kind, which is what the addon wants,
because the type of a `Ciphertext<T>` is known to TypeScript alone.

Behaviour is unchanged.
`dynamic::value` had four batch functions: `encrypt_all`,
`decrypt_all` and their forms with a context. Each took one declared
kind for every value, so a batch of values of different kinds could not
use them. And each only did what `Pending::all` does for any pending
calls: merge their key requests into one.

The four functions are removed. The run-time interface is `encrypt`,
`encrypt_with_context`, `decrypt` and `decrypt_with_context`. A binding
makes one call for each value and merges the calls with `Pending::all`.
That is one key request, the results come back in order, and each value
keeps its own declared kind and context. `Pending::all` is public and
works for the decrypt calls too, so no new API is needed.

The docs of `encrypt` and `decrypt` each show a batch of values of
different kinds merged into one key request.

The conformance batches stay, and the Rust runner now runs them as a
binding does, through `Pending::all`. Each batch lists a declared kind
for each input, and a new batch mixes kinds. The tests keep "a batch
makes one key request" and "a refused value stops the batch before any
key request", and drop the ones that only exercised the removed
functions.
The run-time single-value encrypt reported a refused value as
`dynamic::Error::Source`, whose message begins "record source does not
fit the plan". A single value has no record and no plan, so the message
told the caller about things their call does not have.

A refusal is now `dynamic::Error::Value { reason }`, with the code
`stack_encrypt::dynamic_value`. Its message is about one value: "the
value cannot be encrypted as one ciphertext", then what was found. It
names no field. The reasons and their names are unchanged.

Two reasons have phrases written for a record's field: a value of
another type ("... than its field declares") and `undefined` ("...
where its field declares a type"). The new variant words those two for
a value, and leaves the phrases themselves alone, so a record's
messages do not change.

The Go guest classes the new variant as the caller's input, as it does
a source refusal. Without that it would fall to the catch-all and be
reported as an engine fault. The conformance cases expect the new code.

Decrypt refusals are unchanged: a value of another kind is still
`Error::OpenedType`.
`ScalarTarget` was an open marker with one impl for each kind of target.
That left two faults. A newtype that derives `Decrypt` over a scalar,
such as `struct Email(String)`, did not carry it, so its author had to
write `impl ScalarTarget for Email {}` to decrypt it from one
ciphertext. And nothing stopped the same line for a target that reads
only a container, which then compiled and refused every leaf.

The marker now sits on sinks. `TakesScalar` means one scalar satisfies
the sink, and the sinks that read a scalar carry it: `ScalarSink`,
`ScalarProtected` and `OwnedFrameSink`, and `Optional`,
`ProtectedOptional`, `Wrapped` and `Wrap` over a sink that carries it.
`ScalarTarget` has one blanket impl, for every target whose sink is
marked. A derived newtype's sink is `Wrapped` over its inner type's
sink, so a newtype of a scalar is a `ScalarTarget` with no code, and a
newtype of a `Vec<String>` is not.

No one can implement `ScalarTarget` by hand. The blanket impl does not
ensure that alone: the compiler accepts a second impl for a type whose
sink is defined in the same crate as that impl, because it can see the
sink is not marked. The sink `#[derive(Decrypt)]` generates for a struct
with named fields is such a sink. So `ScalarTarget` also has a private
supertrait that holds only for a target whose sink is marked. A
compile-fail test pins both cases.

A sink written by hand opts in by implementing `TakesScalar`. That is
the one promise the compiler still does not check.

`ScalarTarget` and `TakesScalar` carry `diagnostic::on_unimplemented`.
The error for `keyset.decrypt::<Vec<String>>` now says that one
ciphertext holds one value, and names what to decrypt instead: a
`Vec<Ciphertext>` element by element, or a tree with `decrypt_tree`.

stack-encrypt's docs, changelog and ADR amendment no longer tell a
newtype's author to write the marker, and its compile tests cover a
derived newtype with no marker.

BREAKING CHANGE: `ScalarTarget` can no longer be implemented directly.
Remove any `impl ScalarTarget for T {}`. A derived newtype of a scalar
needs none, and a target with a sink of its own implements
`TakesScalar` for that sink.
The prose that this branch added was hard to read. Its reader is a
developer who knows Rust, but who was not part of this work. The prose
used the terms frame, kind, leaf, sink, and refusal without defining
them. Many
sentences had two ideas. Things were given a person's verb: a
ciphertext "holds" a value, and a binding "knows" a kind.

This commit rewrites that prose to follow the plain-language skill. The
checker of the skill reports no "must fix" finding for the rewritten
prose. Each doc comment, document, or changelog entry defines a term
where it first uses that term. Each sentence has one idea. Lists
replace long sentences that named many items.

The rewrite covers these places:

- the rustdoc and comments of `dynamic::value`, of the error enum, and
  of `ScalarTarget` and `TakesScalar`
- the comments of the tests
- the conformance contract and README
- the two changelogs, the binding guide, and the ADR amendment

Three message strings change. Each was written on this branch, with the
same faults:

- The help text of `Error::Value` says that one ciphertext "contains"
  one value.
- The message of `Error::Value` for a value of another kind is "it does
  not convert exactly to the declared kind". The test that pins the
  message changes to match.
- The compile error for a target that is not a scalar target says "`T`
  cannot be decrypted from one ciphertext". Each note of that error is
  one sentence. The compile-fail snapshots are recorded again.

The conformance contract writes "issue #2010" where it wrote "#2010".
The README has its sentence about the single-value cases in a paragraph
of its own. No error code, reason, or stored byte changes.
@coderdan

Copy link
Copy Markdown
Contributor Author

The two findings outside the diff are fixed too.

  • Refusal wording (refusal.rs). A single-value refusal now has its own variant, dynamic::Error::Value, with the code stack_encrypt::dynamic_value (d81ba19). Its message is about one value, with no record or plan in it. The Go guest's status mapping, the conformance cases and the CHANGELOG are updated.
  • ADR-0012. Amended in bf9b705: a single Ciphertext's target is now a scalar, checked at compile time.

The branch's prose is also rewritten in plain language (5c2cbc4).

The compile error for `keyset.decrypt::<Vec<String>>` named Vitamin C
internals. The error said that `TakesScalar` is not implemented for
`vitaminc_aead::typed::List<String>`, and listed the other sinks. A user
of Stack Encrypt wrote `Vec<String>`, and has never used a sink.

The blanket impl of `OpaqueDecode` now has
`#[diagnostic::do_not_recommend]`. The compiler then reports the refused
type against `OpaqueDecode`, and stops there. `OpaqueDecode` has a
message of its own. The error reads "`Vec<String>` cannot be decrypted
from one `Ciphertext`", and its notes say:

- what one `Ciphertext` decrypts into
- that the type must also be `Zeroize`, `Send`, and `'static`
- what to use for a `Vec<Ciphertext>`, for a sequence, a map, or a
  struct, and for a whole `Deserialize` value

The attribute hides which bound failed. So the notes list every bound,
and none of them says that the type is a container. A new compile-fail
test pins the error for a derived newtype of a `String` with no
`Zeroize` impl.

Vitamin C's own messages change to match. The blanket impls of
`ScalarTarget` and of its sealed supertrait have the same attribute. A
caller with a `T: ScalarTarget` bound now gets "`Vec<String>` is not
built from one scalar", with the target named. A hand-written impl gets
"`ScalarTarget` cannot be implemented for `Account`". These messages no
longer mention `Ciphertext` or `decrypt_tree`, because those are Stack
Encrypt's names.

The same message now covers `OpaqueBlob<T>` when `T` lacks `Default` or
`Zeroize`, so its last note names those two bounds.
The note on a refused decrypt target said "an integer other than u8".
usize and isize are refused too, so the note now says "a fixed-width
integer other than u8", as the encrypt side's note does.
@coderdan
coderdan marked this pull request as ready for review November 28, 2026 09:08
@coderdan
coderdan requested a review from a team as a code owner November 28, 2026 09:08

@cipherstash-agent cipherstash-agent left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review attestation

Reviewed 2e6b6018 · posted from Claude Code · claude-opus-5-5 · effort medium
Sources: code-review · claude-opus-5-5; mattpocock-skills:code-review agent · claude-opus-5-5; rust-security agent · claude-opus-5-5
Skills: code-review, company-skills:rust-security, mattpocock-skills:code-review, company-skills:review-cross-check

Findings (3): 3 minor — 1 inline, 2 below.

  • packages/stack-encrypt/src/scalar.rs:120, packages/stack-encrypt/CHANGELOG.md:581 minor Both say every scalar target includes "the integers". u8 is not a target (vitaminc-aead/src/typed.rs:602), so keyset.decrypt::<u8>(ct) fails with E0277, against the docs. Say "the integers except u8", as ScalarTarget's own doc and the diagnostic do.
  • packages/stack-encrypt/src/scalar.rs:158, scalar.rs:115, packages/stack-encrypt/CHANGELOG.md:588 minor These say a type of your own qualifies when it is built from one scalar and implements Zeroize. They leave out the Send + 'static bound (scalar.rs:215, :252), so a scalar newtype holding a *const () or a &'a str is refused, and the borrowed case gets a plain lifetime error, not the diagnostic note. Add "and is Send and 'static".

The rust-security pass found nothing: refusals happen before any key request, the context binds the same way on the typed and run-time paths, and errors carry no plaintext. Not run here: trybuild snapshots, clippy, the vitaminc-aead suite, the recipher-js addon and the Go guests.


Generated by Claude Code

Comment thread packages/stack-encrypt/src/scalar.rs Resolved
A second review found three statements about decrypt targets that were
wrong or incomplete.

The first note of the compile error for `OpaqueDecode` read as a full
list of the accepted types. The note left out several of them. A user
who wrote `keyset.decrypt::<uuid::Uuid>` saw the note, and nothing told
them to use `value::Uuid`.

The note now says that its list is partial, and names the docs of
`OpaqueDecode` for the full list. A new note names `value::Date`,
`value::Timestamp`, `value::Decimal`, and `value::Uuid`. The same note
says why the jiff, rust_decimal, and uuid types are refused: each is
built from one scalar, but none implements `Zeroize`.

The docs and the changelog said that every integer is a target. `u8`,
`usize`, and `isize` are not. The text now says "the fixed-width
integers other than `u8`".

The docs and the changelog said that a type of your own needs one scalar
and `Zeroize`. The blanket impl also needs `Send` and `'static`. The
text now lists every bound, and says that a `'static` type borrows no
data.

The compile-fail test for a target with no `Zeroize` now also covers
`uuid::Uuid`.
@coderdan

Copy link
Copy Markdown
Contributor Author

The two findings in the review body are fixed in 25e344a.

  • "The integers". scalar.rs and the CHANGELOG now say "the fixed-width integers other than u8". The same claim was in ScalarTarget's rustdoc in vitaminc-aead, and it is fixed there too. usize and isize are not targets: I compiled keyset.decrypt::<usize> to check.
  • Send and 'static. The OpaqueDecode docs and the CHANGELOG now list every bound: built from one scalar, and Zeroize, Send and 'static. The docs explain that "a 'static type borrows no data".

One limit: a target that fails only 'static gets rustc's lifetime error ("requires that 'a must outlive 'static"), not this message. rustc reports a lifetime as a lifetime error, so no on_unimplemented text can apply. The docs are correct for that case.

Four files conflicted. Each resolution keeps the work of both branches.

- refusal.rs: the error docs keep the text from next about the kind found,
  the row, and Debug. The list of variants with a reason now names both
  SourceFailed and Value. The message helpers from both branches stay.
  reason() returns the reason of Value and of SourceFailed.
- codes.rs: the code test builds both Error::Value and Error::SourceFailed.
- The Go guest's status.rs maps both Value and SourceFailed to the status
  for bad input, and its test checks both.
- The stack-encrypt CHANGELOG lists the breaking entry for the scalar bound
  on decrypt, then the two breaking entries from next.

No other file needed a change. The messages of Error::Value use no text
that next changed, and the conformance cases check codes and reasons only.
A refusal from `dynamic::value::encrypt` now names the kind of the value
to encrypt, as a `dynamic::Found`. The record errors already name a kind
in this way, and one rule for both is simpler for a language SDK.

- `Error::Value` has a new field, `found`. The kind is in `found()`, in
  the payload field `found`, and in the message.
- An array, an object, a null, a passthrough, and `undefined` share the
  new reason `not_a_scalar`. The reasons `array`, `object`, and `null`
  are removed. Nothing else used them.
- The kind is always the kind of the input. A refused decrypt still names
  only the kind that was expected.
- Each refused case of `single-value-v1` checks `found` as well as `code`
  and `reason`.
@coderdan

Copy link
Copy Markdown
Contributor Author

dynamic::Error::Value now names the kind of the value to encrypt, as a dynamic::Found. Dan decided this on this PR, so that a single-value refusal names a kind in the same way as the record errors of #2005.

What changed:

  • Error::Value has a new field, found. The kind is in Error::found(), in the payload field found, and in the message. An example message is "the value to encrypt is an array, not a scalar".
  • The three reasons array, object, and null are removed. Nothing else used them. An array, an object, a null, a passthrough, and undefined now share one new reason, not_a_scalar. found says which of them the value is. Before this change, a passthrough had the reason passthrough. undefined had the reason undefined.
  • A value of another kind keeps the reason field_type. Text that is not a JSON document keeps its JSON reason. Both now name the kind of the input as well.
  • found is only the kind of the value that the caller sent. A refused decrypt is still OpenedType. That error names only the kind that was expected.
  • Each refused case in single-value-v1 now checks found as well as code and reason. The Go runner for Go SDK: encrypt one value into one ciphertext, as Rust and TypeScript do #2010 will check the same three fields. The contract document, docs/language-integration.md, the rustdoc, and the CHANGELOG entry say the same.
  • The Go guest's status mapping is unchanged. The guest's test builds the new form of the error. The TypeScript addon reads no reasons, so it did not change.

Commit: dacd89c.

@coderdan
coderdan merged commit 6d1dd69 into next Nov 29, 2026
68 of 69 checks passed
@coderdan
coderdan deleted the feat/dynamic-single-value branch November 29, 2026 04:48
coderdan added a commit that referenced this pull request Nov 29, 2026
Brings in #2011, the run-time single-value API and the scalar bound on
typed decrypt.

Both pull requests changed the trybuild snapshots
owned_collection_elements.stderr and opaque_blob_requires_zeroize.stderr.
Git merged them without a conflict. Recording them again with
TRYBUILD=overwrite on Rust 1.94.1 gave the same files. The encrypt errors
are from this branch. The decrypt errors are from #2011.
coderdan added a commit that referenced this pull request Nov 29, 2026
Brings in #2011 and the OpaqueDebug change. Next added their changelog
entries under [Unreleased]. This branch has no [Unreleased] section, so
the entries now read as part of the upgrade from 0.2.0:

- stack-encrypt 0.3.0, Added: the run-time single-value API, as #2011
  wrote it.
- stack-encrypt 0.3.0, Added: the scalar bound on typed decrypt replaces
  the entry that said a target that is not a scalar compiles.
  `OpaqueDecode` is new in 0.3.0, so the bound is not a break from 0.2.0.
- stack-encrypt 0.3.0, Added: `JsonPlaintext` and `OpaqueBlob<T>` are new
  in 0.3.0. So their entries now say what their `Debug` text is. There is
  no entry for a change of that text.
- stack-kms 0.2.0: the `OpaqueDebug` change for `DataKey` and
  `DataKeyWithTag` is under Refactoring, the heading cliff.toml gives a
  refactor commit. `DeterministicSource` is new in 0.2.0, so its Features
  entry now says what its `Debug` text is.
coderdan added a commit that referenced this pull request Nov 29, 2026
Brings in #2011. Its changes to the Go guest are a new status code for a
refused single value. They do not touch the frame codec that this branch
moves into the module.

One conflict, in tests/value_bytes.rs. Both sides changed the doc
comment and the signature of typed_null_section. The merge keeps the doc
comment from this branch, because that comment no longer names vcvalue.
The merge keeps the signature from next. That signature takes the shared
Kept type for the keys.
coderdan added a commit that referenced this pull request Nov 29, 2026
Brings in #2014 and, through it, next with #2011.

Conflicts:

- stack-encrypt's lib.rs: this branch re-exports `FromScalar` and
  `Scalar`, and #2011 re-exports `ScalarTarget`. The merge re-exports
  all three.
- stack-encrypt's CHANGELOG: both sides added an entry at the top of
  Added. The merge keeps both entries.
- owned_collection_elements.stderr: the merge takes the snapshot of
  #2014. Recording it again with TRYBUILD=overwrite gave the same file.

#2011 added tests and a doc example to vitaminc-aead that use the
derives from vitaminc_aead. On this branch vitaminc-aead has no derives.
So these now use stack_encrypt_derive with
`#[aead(crate = "::vitaminc_aead")]`, as the other vitaminc-aead tests
do:

- tests/scalar_target.rs
- four compile-fail tests in tests/ui/scalar_target/
- the example on `ScalarTarget` in typed.rs

The four snapshots of those compile-fail tests change only in their line
numbers. Two doc comments in typed.rs now say "Stack Encrypt's
`#[derive(Decrypt)]`", as the rest of the file does.
coderdan added a commit that referenced this pull request Nov 29, 2026
Brings in #2011 and its single-value profile.

- coverage.md: both sides changed one row of the table. This branch
  changed the row about scalar widths, and next changed the row about
  owned ciphertexts. The merge keeps both rows as they were changed.
- Both sides added the same `uuid` input type to the shared conformance
  helper, tests/common/conformance.rs. Git merged the two copies into
  one.
- The single-value contract defines the `uuid` input text as this
  branch's README does: lowercase hex in groups of 8, 4, 4, 4, and 12
  digits.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

stack-encrypt: encrypt and decrypt one value whose type is known only at run time, and bound the typed decrypt to a scalar

2 participants